﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UBlockly.Scriptable;
using System;
using System.IO;
using UBlockly;

static class ILFunctionMaker
{
    [MenuItem("BlockTool/生成基础ILFucntion")]
    static void MakeILFunction()
    {
        List<string> list = new List<string>();
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        foreach (var ass in assemblies)
        {
            var types = ass.GetTypes();
            foreach (var tp in types)
            {
                if (!typeof(IBlockApi).IsAssignableFrom(tp))
                    continue;
                var methods = tp.GetMethods();
                foreach (var method in methods)
                {
                    if (!TranslateHelper.IsBlockMethod(method))
                        continue;
                    var str = TranslateHelper.ParseMethodToFuncDefineStr(method);
                    var ilstr = TranslateHelper.ParseFuncTypeStr(str);
                    if (!list.Contains(ilstr))
                    {
                        list.Add(ilstr);
                    }
                }
            }
        }

        GeneratorILFuncTypeFile(list);
        GeneratorILFuncDelegateFile(list);
        AssetDatabase.Refresh();
    }

    static void GeneratorILFuncTypeFile(List<string> list)
    {
        string typeText = "";
        foreach (var p in list)
        {
            typeText += $"{p},";
        }
        string text = @"
namespace UBlockly.Runtime
{
    
    /// <summary>
    /// 函数类型定义（自动生成）
    /// </summary>
    public enum ILFuncType 
    {
        " + typeText
                    + @"
    }
}";
        ;
        //string targetPath = Application.dataPath
        var sw = File.CreateText(Path.Combine(Application.dataPath, "Define.ILFuncType.cs"));
        sw.Write(text);
        sw.Close();
    }

    static void GeneratorILFuncDelegateFile(List<string> list)
    {
        string delegateText = "";
        int index = 1;
        foreach (var p in list)
        {
            var str = p;
            if (p.Contains("_"))
            {
                var pre = str.Substring(0, str.IndexOf('_'));
                str = str.Substring(str.IndexOf('_') + 1) + "_" + pre;
                str = str.Replace("_", ",");
            }

            delegateText += $"public static readonly Func<{str}> func{index++};\n\t\t";
        }
        string text = @"
using System;
using UBlockly.Scriptable;

namespace UBlockly.Runtime
{
    
    /// <summary>
    /// 函数委托类型定义（自动生成）
    /// </summary>
    public class ILFunctionDelegate 
    {
        " + delegateText
          + @"
    }
}";
        var sw = File.CreateText(Path.Combine(Application.dataPath, "Define.ILFuncDelegate.cs"));
        sw.Write(text);
        sw.Close();
    }
}

